import request from "@/utils/request"
import { Environment } from "./environment/type"
import { Instance } from "../docker/type"
import { User } from "../user/type"
import { createExecute } from "../docker"
import { CodeContent, UserEnvironment } from "./type"
import { useMessageStore } from "@/store/message"

export const getUserEnvironmentList = (userId: string) => {
    return request.get("/code/list", {
        params: {
            "userId": userId
        }
    })
}

export const createUserEnvironment = (name: string, user: User, instance: Instance, environment: Environment) => {
    return request.post("/code/create", {
        "name": name,
        "user": user,
        "instance": instance,
        "environment": environment
    })
}

export const stopCode = (codeId: string) => {
    return request.post("/code/stop", {
        "codeId": codeId,
    })
}

export const runCode = async (codeId: string, content: string) => {
    const res = await getCodeInfoByCodeId(codeId);
    const code = res.data as UserEnvironment;
    const execute = await createExecute(code.instance.id, code.containerId);
    const executeId = execute.data as string;
    const messageStore = useMessageStore();
    messageStore.publish("/execute/message/"+executeId);
    console.log("开始监听：", "/execute/message/"+executeId);
    return request.post("/code/run", {
        "codeId": codeId,
        "executeId": executeId,
        "content": content
    });
}

export const getEnvironmentInfoByCodeId = (id: string) => {
    return request.get("/code/environment/info", {
        params: {
            "codeId": id
        }
    })
}

export const getCodeInfoByCodeId = (codeId: string) => {
    return request.get("/code/info", {
        params: {
            "codeId": codeId
        }
    })
}

export const getCodeContent = (codeId: string) => {
    return request.get("/code/content", {
        params: {
            "codeId": codeId
        }
    })
}

export const saveCodeContent = (codeContent: CodeContent) => {
    return request.post("/code/content/save", codeContent);
}